<template>
  <div class="h-screen w-full bg-black overflow-hidden relative">
    <!-- 视频播放器容器 -->
    <div ref="videoContainer" class="h-full w-full overflow-y-scroll snap-y snap-mandatory scroll-smooth"
      @scroll="handleScroll">
      <!-- 视频列表 -->
      <div v-for="(video, index) in videos" :key="video.id" class="w-full h-full snap-start relative">
        <!-- 视频播放器 -->
        <video ref="videoPlayers" :data-index="index" :src="video.url" class="w-full h-full object-cover" preload="auto"
          playsinline webkit-playsinline @canplay="onVideoCanPlay(index)" @ended="onVideoEnded(index)"
          @error="onVideoError(index)"></video>

        <!-- 视频信息 -->
        <div class="absolute bottom-0 left-0 p-4 text-white w-full bg-gradient-to-t from-black/80 to-transparent">
          <div class="flex items-center mb-2">
            <div class="bg-gray-200 border-2 border-dashed rounded-xl w-10 h-10" />
            <div class="ml-3">
              <p class="font-bold">@{{ video.author }}</p>
              <p class="text-sm">{{ video.description }}</p>
            </div>
          </div>
          <div class="flex items-center mt-3 space-x-4">
            <div class="text-center">
              <button class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
              </button>
              <p class="text-xs mt-1">{{ video.likes }}</p>
            </div>
            <div class="text-center">
              <button class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
              </button>
              <p class="text-xs mt-1">{{ video.comments }}</p>
            </div>
            <div class="text-center">
              <button class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                  stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                </svg>
              </button>
              <p class="text-xs mt-1">{{ video.shares }}</p>
            </div>

            <!-- 静音按钮 -->
            <button class="text-white ml-4 transition-all duration-300 transform hover:scale-110" @click="toggleMute">
              <svg v-if="isMuted" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M17 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2" />
              </svg>
              <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M15.536 8.464a5.001 5.001 0 010 7.072M12 6a9 9 0 010 12m-4.5-9.5L12 3l6.5 6.5M4 14l4.5 4.5L12 21l3.5-3.5L20 14" />
              </svg>
              <span class="text-xs">{{ isMuted ? '开启声音' : '关闭声音' }}</span>
            </button>

          </div>
        </div>

        <!-- 加载指示器 -->
        <div v-if="!video.loaded" class="absolute inset-0 flex items-center justify-center">
          <div class="w-16 h-16 border-t-4 border-blue-500 border-solid rounded-full animate-spin"></div>
        </div>
      </div>

      <!-- 加载更多指示器 -->
      <div v-if="loadingMore" class="w-full h-20 flex items-center justify-center">
        <div class="w-12 h-12 border-t-4 border-blue-500 border-solid rounded-full animate-spin"></div>
      </div>
    </div>

    <!-- 顶部导航 -->
    <div class="absolute top-0 left-0 w-full p-4 flex justify-between z-10">
      <button class="text-white font-bold">Following</button>
      <div class="flex space-x-4">
        <button class="text-white">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </button>
        <button class="text-white">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        </button>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="absolute bottom-4 right-4 flex flex-col items-center space-y-6">
      <div class="text-center">
        <div class="w-12 h-12 rounded-full bg-gradient-to-r from-pink-500 to-yellow-500 p-0.5">
          <div class="bg-black rounded-full w-full h-full flex items-center justify-center">
            <div class="bg-gray-200 border-2 border-dashed rounded-xl w-8 h-8" />
          </div>
        </div>
        <div class="w-1 h-6 bg-white mx-auto mt-1"></div>
      </div>
      <button class="text-white text-center">
        <div class="w-12 h-12 rounded-full bg-white/20 flex items-center justify-center">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
              d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z" />
          </svg>
        </div>
        <p class="text-xs mt-1">More</p>
      </button>
    </div>
    <!-- 声音提示 -->
    <div v-if="showSoundPrompt" class="absolute inset-0 flex items-center justify-center bg-black/70 z-20">
      <div class="bg-gray-900 p-6 rounded-xl max-w-sm text-center">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto text-blue-500 mb-4" fill="none"
          viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
            d="M15.536 8.464a5.001 5.001 0 010 7.072M12 6a9 9 0 010 12" />
        </svg>
        <h3 class="text-white text-xl font-bold mb-2">视频声音已关闭</h3>
        <p class="text-gray-300 mb-4">点击右上角的声音按钮开启声音</p>
        <button class="bg-blue-600 hover:bg-blue-700 text-white py-2 px-6 rounded-full font-medium"
          @click="hideSoundPrompt">
          知道了
        </button>
      </div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';

definePageMeta({
  layout: 'minimal',
  showHeader: false
});

interface VideoItem {
  id: number;
  url: string;
  author: string;
  description: string;
  likes: string;
  comments: string;
  shares: string;
  loaded: boolean;
  played: boolean;
}

// 使用可靠的测试视频URL
const testVideoUrls = [
  'https://www.runoob.com/try/demo_source/movie.mp4',
  'https://videos.pexels.com/video-files/853908/853908-hd_1920_1080_25fps.mp4',
  'https://www.runoob.com/try/demo_source/mov_bbb.mp4',
  'https://media.w3.org/2010/05/sintel/trailer.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/16/20200216050645YIMfjPq5Nw.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/16/20200216050645YIMfjPq5Nw.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/17/20200217101826WjyFCbUXQ2.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218114723HDu3hhxqIT.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218093206z8V1JuPlpe.mp4',
  'https://stream7.iqilu.com/10339/article/202002/18/2fca1c77730e54c7b500573c2437003f.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218025702PSiVKDB5ap.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/18/202002181038474liyNnnSzz.mp4',
  'https://stream7.iqilu.com/10339/article/202002/18/02319a81c80afed90d9a2b9dc47f85b9.mp4',
  'http://stream4.iqilu.com/ksd/video/2020/02/17/c5e02420426d58521a8783e754e9f4e6.mp4',
  'http://stream4.iqilu.com/ksd/video/2020/02/17/87d03387a05a0e8aa87370fb4c903133.mp4',
  'https://stream7.iqilu.com/10339/article/202002/17/c292033ef110de9f42d7d539fe0423cf.mp4',
  'http://stream4.iqilu.com/ksd/video/2020/02/17/97e3c56e283a10546f22204963086f65.mp4',
  'https://stream7.iqilu.com/10339/article/202002/17/778c5884fa97f460dac8d90493c451de.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/17/20200217021133Eggh6zdlAO.mp4',
  'https://stream7.iqilu.com/10339/article/202002/17/4417a27b1a656f4779eaa005ecd1a1a0.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/17/20200217104524H4D6lmByOe.mp4',
  'https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209104902N3v5Vpxuvb.mp4'
];

// 生成固定的视频数据，解决 hydration 问题
const generateVideos = (start: number, count: number): VideoItem[] => {
  const videos: VideoItem[] = [];
  for (let i = 0; i < count; i++) {
    const id = start + i;
    // 循环使用测试URL
    const url = testVideoUrls[i % testVideoUrls.length];

    videos.push({
      id,
      url,
      author: `user_${id}`,
      description: `Video #${id}`,
      likes: `${Math.floor(Math.random() * 1000)}K`,
      comments: `${Math.floor(Math.random() * 500)}`,
      shares: `${Math.floor(Math.random() * 200)}`,
      loaded: false,
      played: false
    });
  }
  return videos;
};

const videos = ref<VideoItem[]>([]);
const videoPlayers = ref<HTMLVideoElement[]>([]);
const videoContainer = ref<HTMLDivElement | null>(null);
const currentIndex = ref(0);
const loadingMore = ref(false);
const page = ref(1);
const pageSize = 5;
const isMuted = ref(true); // 初始为静音状态
const showSoundPrompt = ref(true); // 是否显示声音提示

// 当前视频播放状态
const currentVideo = ref<VideoItem | null>(null);

// 切换静音状态
const toggleMute = () => {
  isMuted.value = !isMuted.value;

  // 保存用户偏好到本地存储
  localStorage.setItem('videoMutePreference', isMuted.value.toString());

  // 更新所有视频的静音状态
  videoPlayers.value.forEach(player => {
    if (player) {
      player.muted = isMuted.value;
    }
  });
};

// 隐藏声音提示
const hideSoundPrompt = () => {
  showSoundPrompt.value = false;
};


// 播放指定索引的视频
const playVideo = (index: number) => {
  // 确保索引有效
  if (index < 0 || index >= videos.value.length) return;

  // 暂停所有视频
  videoPlayers.value.forEach(player => {
    if (player) player.pause();
  });

  // 播放当前视频
  if (videoPlayers.value[index]) {
    const player = videoPlayers.value[index];

    // 尝试播放
    const playPromise = player.play();
    if (playPromise !== undefined) {
      playPromise.catch(e => {
        console.error('Autoplay failed:', e);
        // 处理自动播放失败的情况 - 静音后重试
        player.muted = true;
        player.play().catch(console.error);
      });
    }

    currentIndex.value = index;
    currentVideo.value = videos.value[index];
    videos.value[index].played = true;
  }
};

// 滚动处理
const handleScroll = () => {
  if (!videoContainer.value) return;

  const container = videoContainer.value;
  const scrollTop = container.scrollTop;
  const containerHeight = container.clientHeight;

  // 计算当前视频索引
  const index = Math.floor(scrollTop / containerHeight);

  // 确保索引在有效范围内
  if (index < 0 || index >= videos.value.length) return;

  // 如果索引发生变化，播放新视频
  if (index !== currentIndex.value) {
    playVideo(index);

    // 预加载相邻视频
    preloadAdjacentVideos(index);

    // 检查是否需要加载更多
    checkLoadMore(index);
  }
};

// 预加载相邻视频
const preloadAdjacentVideos = (currentIndex: number) => {
  // 预加载前一个视频
  const prevIndex = currentIndex - 1;
  if (prevIndex >= 0 && !videos.value[prevIndex].loaded) {
    const player = videoPlayers.value[prevIndex];
    if (player) {
      player.load();
    }
  }

  // 预加载后一个视频
  const nextIndex = currentIndex + 1;
  if (nextIndex < videos.value.length && !videos.value[nextIndex].loaded) {
    const player = videoPlayers.value[nextIndex];
    if (player) {
      player.load();
    }
  }
};

// 检查是否需要加载更多视频
const checkLoadMore = (currentIndex: number) => {
  // 当滚动到倒数第三个视频时加载更多
  if (currentIndex >= videos.value.length - 3 && !loadingMore.value) {
    loadMoreVideos();
  }
};

// 加载更多视频
const loadMoreVideos = async () => {
  loadingMore.value = true;

  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 1000));

  const startId = videos.value.length > 0
    ? Math.max(...videos.value.map(v => v.id)) + 1
    : 1;

  const newVideos = generateVideos(startId, pageSize);

  // 添加新视频到列表
  videos.value = [...videos.value, ...newVideos];

  loadingMore.value = false;

  // 等待DOM更新
  nextTick(() => {
    // 继续预加载
    preloadAdjacentVideos(currentIndex.value);
  });
};

// 视频可以播放事件
const onVideoCanPlay = (index: number) => {
  videos.value[index].loaded = true;

  // 如果是当前视频，尝试播放
  if (index === currentIndex.value && !videos.value[index].played) {
    playVideo(index);
  }
};

// 视频播放结束事件
const onVideoEnded = (index: number) => {
  // 如果当前视频播放结束，播放下一个
  if (index === currentIndex.value && index < videos.value.length - 1) {
    // 滚动到下一个视频
    if (videoContainer.value) {
      const container = videoContainer.value;
      const nextPosition = (index + 1) * container.clientHeight;

      container.scrollTo({
        top: nextPosition,
        behavior: 'smooth'
      });
    }
  }
};

// 视频加载错误处理
const onVideoError = (index: number) => {
  console.error(`Error loading video at index ${index}`);
  // 标记为已加载以防止无限加载指示器
  videos.value[index].loaded = true;
};

// 初始化
onMounted(() => {
  isMuted.value = true; // 初始为静音状态
  showSoundPrompt.value = true; // 是否显示声音提示
  // 初始化视频数据
  videos.value = generateVideos(1, pageSize);

  // 等待DOM更新
  nextTick(() => {
    // 初始预加载
    preloadAdjacentVideos(0);

    // 尝试播放第一个视频
    playVideo(0);

    // 添加键盘事件支持（上/下键切换视频）
    window.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowDown' && currentIndex.value < videos.value.length - 1) {
        const nextIndex = currentIndex.value + 1;
        if (videoContainer.value) {
          videoContainer.value.scrollTo({
            top: nextIndex * videoContainer.value.clientHeight,
            behavior: 'smooth'
          });
        }
        e.preventDefault();
      } else if (e.key === 'ArrowUp' && currentIndex.value > 0) {
        const prevIndex = currentIndex.value - 1;
        if (videoContainer.value) {
          videoContainer.value.scrollTo({
            top: prevIndex * videoContainer.value.clientHeight,
            behavior: 'smooth'
          });
        }
        e.preventDefault();
      }
    });
  });
});
</script>

<style scoped>
/* 隐藏滚动条 */
::-webkit-scrollbar {
  display: none;
}

/* 强制视频全屏 */
video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 平滑滚动 */
.scroll-smooth {
  scroll-behavior: smooth;
}

/* 捕捉滚动 */
.snap-y {
  scroll-snap-type: y mandatory;
}

.snap-start {
  scroll-snap-align: start;
}

/* 确保视频容器有高度 */
.h-screen {
  height: 100vh;
}
</style>